import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export const useServerBootSettings = defineStore('serverBootSettings', () => {
  const bootSourceOptions = ref([] as any[]);
  const bootSource = ref();
  const overrideEnabled = ref(false);
  const tpmEnabled = ref();

  const setBootSourceOptions = (Options: any) =>
    (bootSourceOptions.value = Options);
  const setBootSource = (Source: any) => (bootSource.value = Source);
  const setOverrideEnabled = (Enabled: string) => {
    if (Enabled === 'Once') {
      overrideEnabled.value = true;
    } else {
      // 'Continuous' or 'Disabled'
      overrideEnabled.value = false;
    }
  };
  const setTpmPolicy = (Enabled: any) => (tpmEnabled.value = Enabled);

  const getBootSettings = async () => {
    return await api
      .get('/redfish/v1/Systems/system')
      .then(({ data: { Boot } }) => {
        setBootSourceOptions(
          Boot['BootSourceOverrideTarget@Redfish.AllowableValues'],
        );
        setOverrideEnabled(Boot.BootSourceOverrideEnabled);
        setBootSource(Boot.BootSourceOverrideTarget);
      })
      .catch((error) => console.log(error));
  };
  const saveBootSettings = ({
    bootSource,
    overrideEnabled,
  }: {
    bootSource: string;
    overrideEnabled: boolean;
  }) => {
    const data: { Boot: { [index: string]: string } } = { Boot: {} };
    data.Boot.BootSourceOverrideTarget = bootSource;

    if (overrideEnabled) {
      data.Boot.BootSourceOverrideEnabled = 'Once';
    } else if (bootSource === 'None') {
      data.Boot.BootSourceOverrideEnabled = 'Disabled';
    } else {
      data.Boot.BootSourceOverrideEnabled = 'Continuous';
    }

    return api
      .patch('/redfish/v1/Systems/system', data)
      .then((response) => {
        // If request success, commit the values
        setBootSource(data.Boot.BootSourceOverrideTarget);
        setOverrideEnabled(data.Boot.BootSourceOverrideEnabled);
        return response;
      })
      .catch((error) => {
        console.log(error);
        // If request error, GET saved options
        getBootSettings();
        return error;
      });
  };
  const getTpmPolicy = async () => {
    // TODO: switch to Redfish when available
    return await api
      .get('/xyz/openbmc_project/control/host0/TPMEnable')
      .then(
        ({
          data: {
            data: { TPMEnable },
          },
        }) => setTpmPolicy(TPMEnable),
      )
      .catch((error) => console.log(error));
  };
  const saveTpmPolicy = (tpmEnabled: any) => {
    // TODO: switch to Redfish when available
    const data = { data: tpmEnabled };
    return api
      .put('/xyz/openbmc_project/control/host0/TPMEnable/attr/TPMEnable', data)
      .then((response) => {
        // If request success, commit the values
        setTpmPolicy(tpmEnabled);
        return response;
      })
      .catch((error) => {
        console.log(error);
        // If request error, GET saved policy
        getTpmPolicy();
        return error;
      });
  };
  const saveSettings = async ({
    bootSource,
    overrideEnabled,
    tpmEnabled,
  }: {
    bootSource: string;
    overrideEnabled: boolean;
    tpmEnabled: boolean;
  }) => {
    const promises = [];

    if (bootSource !== null || overrideEnabled !== null) {
      promises.push(saveBootSettings({ bootSource, overrideEnabled }));
    }
    if (tpmEnabled !== null) {
      promises.push(saveTpmPolicy(tpmEnabled));
    }

    return (await api.all(promises).then(
      api.spread((...responses) => {
        const message = t(
          'pageServerPowerOperations.toast.successSaveSettings',
        );
        responses.forEach((response) => {
          if (response instanceof Error) {
            throw new Error(
              t('pageServerPowerOperations.toast.errorSaveSettings') as string,
            );
          }
        });
        return message;
      }),
    )) as string;
  };
  return {
    bootSourceOptions,
    bootSource,
    overrideEnabled,
    tpmEnabled,
    setBootSourceOptions,
    setBootSource,
    setOverrideEnabled,
    setTpmPolicy,
    getBootSettings,
    saveBootSettings,
    getTpmPolicy,
    saveTpmPolicy,
    saveSettings,
  };
});
